import cv2 as cv
import numpy as np


def translation_affine(image):
    M = np.array([[1,0,10],[0,1,20]],np.float32)
    dst = cv.warpAffine(image,M,image.shape[:2])
    cv.imshow('after translation_affine',dst)


def rotation_affine(image):
    cols,rows = image.shape[:2]
    center = (cols / 2,rows / 2)
    angle,scale = 10, 0.8
    M = cv.getRotationMatrix2D(center,angle,scale)
    dst = cv.warpAffine(image,M,(cols,rows))
    cv.imshow('after rotation_affine', dst)


def affine_transform(image):
    dsize = image.shape[:2]
    pts1 = np.float32([[10,10],[100,200],[200,100]])
    pts2 = np.float32([[10,20],[120,200],[200,100]])
    matrix = cv.getAffineTransform(pts1,pts2)
    dst = cv.warpAffine(image,matrix,dsize)
    cv.imshow('affine transform',dst)


def perspective_affine(image):
    gray = cv.cvtColor(image,cv.COLOR_BGR2GRAY)
    binary = cv.adaptiveThreshold(gray,255,cv.ADAPTIVE_THRESH_MEAN_C,cv.THRESH_BINARY_INV,9,5)
    # cv.imshow('binary', binary)
    kenerl = cv.getStructuringElement(cv.MORPH_RECT,(3,3))
    morphology = cv.morphologyEx(binary,cv.MORPH_ERODE,kenerl,iterations=1)
    # cv.imshow('morphology',morphology)
    contours,hirarchy = cv.findContours(morphology,cv.RETR_TREE,cv.CHAIN_APPROX_SIMPLE)
    avg = 5000
    max = 0
    max_rect_index = 0
    for i, contour in enumerate(contours):
        temp = cv.contourArea(contour)
        if temp >= avg and temp > max:
            max = temp
            max_rect_index = i
    cv.drawContours(image,contours,max_rect_index,(0,255,255),2)
    # cv.imshow('contour',image)
    hsv = cv.cvtColor(image,cv.COLOR_BGR2HSV)
    ranged = cv.inRange(hsv,(26,43,46),(34,255,255))
    # cv.imshow('ranged', ranged)
    morphology2 = cv.morphologyEx(ranged, cv.MORPH_ERODE, kenerl, iterations=1)
    # cv.imshow('morphology2', morphology2)
    ranged_float = np.float32(morphology2)
    corners = cv.cornerHarris(ranged_float,2,3,0.04,cv.BORDER_DEFAULT)

    kenerl2 = cv.getStructuringElement(cv.MORPH_RECT, (5, 5))
    dst = cv.dilate(corners,kenerl2)
    image[dst > 0.05 * dst.max()] = [0, 0, 255]
    # cv.circle(image,(69,512),10,(0,0,255),2)
    cv.imshow('dst', image)

    # pts1 = np.float32([[56, 65], [368, 52], [28, 387], [389, 390]])
    # pts2 = np.float32([[0, 0], [300, 0], [0, 300], [300, 300]])
    # M = cv.getPerspectiveTransform(pts1, pts2)
    # dst = cv.warpPerspective(image,M,(300,300))
    # cv.imshow('affine perspective',dst)


# src = cv.imread('lena.jpg')
src = cv.imread('sudoku.png')
cv.namedWindow('demo',cv.WINDOW_AUTOSIZE)
cv.imshow('demo',src)
# translation_affine(src)
# rotation_affine(src)
# affine_transform(src)
perspective_affine(src)
cv.waitKey(0)
cv.destroyAllWindows()